package com.aids_malaria.ui.datacollect;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.aids_malaria.R;
import com.aids_malaria.adapter.DataQueryAdapter;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.base.BaseQuickAdapter;
import com.aids_malaria.http.response.AreaC;
import com.aids_malaria.event.Events;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.DataQueryResponse;
import com.aids_malaria.http.response.MedicalTreatment;
import com.aids_malaria.http.response.MemberData;
import com.aids_malaria.util.AuthUtil;
import com.aids_malaria.util.DateUtil;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.ToastUtil;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.google.gson.Gson;
import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class DataQueryActivity extends BaseActivity {

    public static final String AREA_CODE = "area_code";

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;

    @BindView(R.id.et_county_name)
    TextView et_county_name;
    @BindView(R.id.et_village_name)
    TextView et_village_name;
    @BindView(R.id.et_age_from)
    EditText et_age_from;
    @BindView(R.id.et_age_to)
    EditText et_age_to;
    @BindView(R.id.cb_male)
    CheckBox cb_male;
    @BindView(R.id.cb_female)
    CheckBox cb_female;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.et_id)
    EditText et_id;
    @BindView(R.id.et_identity)
    EditText et_identity;
    @BindView(R.id.et_num)
    EditText et_num;
    @BindView(R.id.et_sick_from)
    TextView et_sick_from;
    @BindView(R.id.et_sick_to)
    TextView et_sick_to;


    private DataQueryAdapter dataQueryAdapter;
    private List<DataQueryResponse> mData = new ArrayList<>();

    private String areaCode = "";

    private String county_code = "";
    private String county_name = "";
    private String village_code = "";
    private MemberData menberData = null;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_data_query;
    }

    @Override
    protected void initView() {
        super.initView();
        tv_title.setText(getString(R.string.data_query_detail));
        initRefreshLayout();
    }

    @Override
    protected void initData() {
        super.initData();
        areaCode = getIntent().getStringExtra(AREA_CODE);
        menberData = GsonUtil.gsonToBean(getIntent().getStringExtra("MemberData"),MemberData.class);
        initRecycleView();
        if (!TextUtils.isEmpty(areaCode)) {
            // area_code不为空
            getPersonGatherInfo();
            MedicalTreatment medicalTreatment = (MedicalTreatment) getIntent().getSerializableExtra("MedicalTreatment");
            if (medicalTreatment != null){
                String county_name = getIntent().getStringExtra("county_name");
                if (medicalTreatment.getArea_code().length() == 1){
                    //县
                    et_county_name.setText(!TextUtils.isEmpty(medicalTreatment.getArea_name())
                            ? medicalTreatment.getArea_name() : county_name);
                }else if (medicalTreatment.getArea_code().length() == 5){
                    //村
                    et_county_name.setText(county_name);
                    et_village_name.setText(medicalTreatment.getArea_name());
                }
            }
        }
        if (null != menberData){
            if (menberData.getArea_code().length() == 1){
                //县
                et_county_name.setText(menberData.getArea_name());
            }else if (menberData.getArea_code().length() == 5){
                //村
                et_village_name.setText(menberData.getArea_name());
            }
        }
    }

    @OnClick({R.id.ll_back, R.id.iv_search, R.id.iv_end_time_select, R.id.iv_start_time_select, R.id.iv_county_select, R.id.iv_village_select
    ,R.id.et_county_name,R.id.et_village_name,R.id.et_sick_from,R.id.et_sick_to})
    public void onClick(View view) {
        Bundle bundle = null;
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.iv_search:
                getPersonGatherInfo();
                break;
            case R.id.iv_start_time_select:
            case R.id.et_sick_from:
                DateUtil.newTimeSelect(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        et_sick_from.setText(DateUtil.getFullTimeFormatter().format(date));
                    }
                }).show();
                break;
            case R.id.iv_end_time_select:
            case R.id.et_sick_to:
                DateUtil.newTimeSelect(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        et_sick_to.setText(DateUtil.getFullTimeFormatter().format(date));
                    }
                }).show();
                break;
            case R.id.iv_county_select:
            case R.id.et_county_name:
                bundle = new Bundle();
                bundle.putInt(Events.TYPE_KEY, Events.TYPE_DATA_QUERY);
                startActivity(CountySelectActivity.class, bundle);
                break;
            case R.id.iv_village_select:
            case R.id.et_village_name:
                bundle = new Bundle();
                bundle.putInt(Events.TYPE_KEY, Events.TYPE_DATA_QUERY);
                bundle.putString("county_code", county_code);
                bundle.putString("county_name", county_name);
                startActivity(VillageSelectActivity.class, bundle);
                break;
        }
    }

    /**
     * 村选择回调
     *
     * @param villageSelectEvent
     */
    @Subscribe
    public void onCodeEvent(Events.VillageSelectEvent villageSelectEvent) {
        if (villageSelectEvent.getType() == Events.TYPE_DATA_QUERY) {
            village_code = villageSelectEvent.getAreaV().getVillage_code();
            et_village_name.setText(villageSelectEvent.getAreaV().getVillage_name());
        }
    }

    /**
     * 县选择回调
     *
     * @param countySelectEvent
     */
    @Subscribe
    public void onCodeEvent(Events.CountySelectEvent countySelectEvent) {
        if (countySelectEvent.getType() == Events.TYPE_DATA_QUERY) {
            AreaC areaC = countySelectEvent.getAreaC();
            county_code = areaC.getCounty_code();
            county_name = areaC.getCounty_name();
            et_county_name.setText(county_name);

            et_village_name.setText("");
            village_code = "";
        }
    }

    private void initRefreshLayout() {
        refresh_layout.setEnableLoadMore(false);
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getPersonGatherInfo();
            }
        });
    }

    private void initRecycleView() {
        rv_data.setLayoutManager(new LinearLayoutManager(mContext));
        dataQueryAdapter = new DataQueryAdapter(mContext, R.layout.item_data_query, mData);
        dataQueryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Bundle bundle = new Bundle();
                bundle.putInt(DataCollectActivity.BUSY_TYPE, 2);
                bundle.putInt(DataCollectActivity.WAY_COLLECT, 0);
                bundle.putString("identity_code", mData.get(position).getIdentity_code());
                startActivity(DataCollectActivity.class, bundle);
            }
        });
        rv_data.setAdapter(dataQueryAdapter);
    }

    private void getPersonGatherInfo() {
        if (!AuthUtil.isHaveQueryAuthByCode(Constant.COLLECT_TREATMENT_PERSONNEL_ACQUISITION)){
            ToastUtil.showNoPermission();
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("area_code", areaCode);
        if (!TextUtils.isEmpty(county_code)) {
            map.put("area_code", county_code);
        }
        if (!TextUtils.isEmpty(village_code)) {
            map.put("area_code", village_code);
        }
        if(TextUtils.isEmpty(map.get("area_code"))){
            ToastUtil.showToast(getString(R.string.hint_xc_select));
            refresh_layout.finishRefresh();
            return;
        }
        map.put("age_fr", et_age_from.getText().toString().trim());
        map.put("age_to", et_age_to.getText().toString().trim());
        map.put("name", et_name.getText().toString().trim());
        map.put("original_id", et_id.getText().toString().trim());
        map.put("identity_code", et_identity.getText().toString().trim());
        if (cb_male.isChecked() && cb_female.isChecked()) {
            map.put("gender", "0");
        } else if (cb_male.isChecked() && !cb_female.isChecked()) {
            map.put("gender", "1");
        } else if (!cb_male.isChecked() && cb_female.isChecked()) {
            map.put("gender", "2");
        }
        map.put("record_num", et_num.getText().toString().trim());
        map.put("onset_time_fr", et_sick_from.getText().toString().trim());
        map.put("onset_time_to", et_sick_to.getText().toString().trim());
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getPersonGatherInfo(map)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<DataQueryResponse>>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(List<DataQueryResponse> data) throws Exception {
                        LogUtil.d(data.toString());
                        if (data != null) {
                            mData.clear();
                            mData.addAll(data);
                            dataQueryAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    protected void onFinish() {
                        refresh_layout.finishRefresh();
                        getLoadingDialog().dismiss();
                    }
                });
    }

}
